<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/webpage/include/taglib.jsp" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html style="overflow: auto;">
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>植百汇采购单</title>
    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/jquery-1.10.2.min.js"></script>
    <%@ include file="/webpage/include/bootstraptable.jsp"%>
    <%@include file="/webpage/include/treeview.jsp" %>
    <%@include file="warehouseForm.jsp" %>
    <script>
        var ctx = '${ctx}';
    </script>

    <script type="text/javascript" src="${ctxStatic}/plugin/layui2.0/layui.js"></script>
  <%--   <link rel="stylesheet" href="${ctxStatic}/plugin/layui2.0/css/layui.css" media="all"> --%>
  <link rel="stylesheet" href="${ctxStatic}/common/css/app-blue.css" media="all"> 
    
	<script src="${ctxStatic}/common/js/sku.js"></script>
    <script src="${ctxStatic}/common/js/jeeplus.js"></script> 
    <style>
    
        .layui-layer-iframe{
            width: 96%;
        }
          #purchaseOrder .self-adaption-wrap {
                   overflow-x: scroll;
               }
               .self-adaption-wrap::-webkit-scrollbar {
                   display: none;
               }
               #purchaseOrder .self-adaption-input{
                   min-width: 200px;
               }
			div#purchaseOrder {
   			/*border: 1px solid red;*/
    		
            }
        /*调整*/
        .margin-left-3{
        	margin-left:60px;
        }
		.layui-input-block {
		    margin-left: 51px;
		    min-height: 36px;
		}
		.layui-form-label {
		    width: 100px;
		}
		legend {
			border-bottom:0 solid;
		}
		.fixed-table-body {
		    height: auto;
		}
		.remarkRow{
			padding:15px 0px;
		}
		.remark {
		    float: left;
		    display: block;
		    padding: 9px 5px;
		    text-align: right;
		}
		
		.form-input {
		    display: inline-block;
		   /*  width: 100%; */
		    height: 32px;
		    font-size: 14px;
		    line-height: 32px;
		    color: #555555;
		    background-color: #fff;
		    background-image: none;
		    border: 1px solid #ccc;
		    border-radius: 5px;
		    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
		    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
		    padding:2px;
		}
		/*表格中的input列没有上下内边距*/
		.bootstrap-table .table>tbody>tr>td.no-padding {
		    padding: 0 8px 0 !important;
		    vertical-align: middle;
		}
		table.table{
			font-size:14px;
		}
		.btn.table-btn{
			padding:0 6px;
		}
		.wrapper-content {
		    padding: 10px;
		}
		input.noborder {
		    border: none; 
		    outline: none;
		    background: none;
		    box-shadow: none;
		    
		}
	label.label-txt {
	    line-height: 38px;
	    width:90px;
	}
	/*手机端可以拖动*/
/* 	table#purchaseOrder {
	    overflow: scroll;
	} */
	.scrollTable{ 
		white-space: nowrap; 
		overflow: hidden; 
		overflow-x: scroll; 
		-webkit-backface-visibility: hidden; 
		-webkit-overflow-scrolling: touch;
	} 
    </style>
    <script>
    $(document).ready(
        function(){
        var c = $(window.parent.document.body) 
            c.find('.layui-layim-min').hide();
        }
    );
    $(window).unload(function(){
        console.log("Goodbye");
        var c = $(window.parent.document.body) 
            c.find('.layui-layim-min').show();
    });
    </script>


</head>
<body style="width:100%; height:100%; overflow: scroll; -webkit-overflow-scrolling: touch;">
	<div class="wrapper wrapper-content">				
			<div class="row">
				<div class="col-md-12">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<h3 class="panel-title"> 
								<a class="panelButton" href="${ctx}/purchase/purchaseOrder"><i class="ti-angle-left"></i> 返回</a>
								<!-- <span class="panel-title margin-left-3">采购单录入</span> -->
							</h3>
						</div>
						<div class="panel-body">
						    <form class="layui-form" action="">
						        <!--供应商信息start-->
						        <div class="row">
						            <div class="col-xs-12 col-sm-6 col-md-3">
						                <label class="label-txt col-xs-4 col-sm-3">供应商:</label>
						                <div class="layui-input-inline col-xs-8 col-sm-9">
						                    <select id="supplierId" lay-filter="supplierId" name="supplierId" lay-verify="required" lay-search="">
						                        <option value="">直接选择或搜索选择</option>
						                        <c:forEach items="${supplierList}" var="i">
						                            <option value="${i.id}">${i.supplierName}</option>
						                        </c:forEach>
						                    </select>
						                </div>
						            </div>
						            <div class="col-xs-12 col-sm-6 col-md-3">
						                <label class="label-txt col-xs-4 col-sm-3" >供应商合同:</label>
						                <div class="layui-input-inline col-xs-8 col-sm-9">
						                    <select name="contractId" id="contractId" lay-verify="required" lay-search="">
						                        <option value="">直接选择或搜索选择</option>
						                    </select>
						                    <div id="iv" name="iv" style="display:none">
						                        <c:forEach items="${contractList}" var="i">
						                            <input class="a" type="hidden" id="${i.supplierId}" value="${i.id}"
						                                   name="${i.contractName}"></input>
						                        </c:forEach>
						                    </div>
						                </div>
						            </div>
						            
						              <div class="col-xs-12 col-sm-6 col-md-3 margin-left-4">
						                  <label class="label-txt col-xs-4 col-sm-3 ">采购时间:</label>
						                  <div class="layui-input-inline  col-xs-8 col-sm-9">
						                        <input type="text" class="layui-input" id="createDate" placeholder="采购时间">
						                  </div>
						               </div>
						               <script type="text/javascript">
						               layui.use('laydate', function(){
						                 var laydate = layui.laydate;
						                   laydate.render({
						                   elem: '#createDate'
						                   ,type: 'datetime'
						                 });
						               })
						               </script>
						            
						        </div>
						        <!--供应商信息end-->
						    
						        <div class="row remarkRow">
							        <div class="col-xs-12 col-sm-9 col-md-9 ">
							        	 <label class='label-txt col-xs-4 col-sm-3 '>备注:</label>
							            <div class="layui-input-inline col-xs-8 col-sm-11">
							                <textarea id="remarks" name="remarks" placeholder="请输入内容" class="layui-textarea"></textarea>
							            </div>
							        </div>
						        </div>
						         <!-- 工具栏 -->
						         <div id="toolbar">
				                        <a  class="btn btn-primary" href="javascript:;"  onclick="sub()"><i
				                                class="glyphicon glyphicon-plus"></i> 选择SKU</a>
				                        <span  class="btn btn-info"  onclick="create()">
				                            <i class="glyphicon glyphicon-link"></i> 一键导入
				                        </span>
				                        <span  class="btn btn-danger" onclick="subForm()">
				                            <i class="glyphicon glyphicon-save"></i>暂存
				                        </span>
				                </div>
				                <!-- 工具栏 -->
						        <style>
						                #purchaseOrder .self-adaption-wrap {
						                   overflow-x: scroll;
						               }
						               .self-adaption-wrap::-webkit-scrollbar {
						                   display: none;
						               }
						               #purchaseOrder .self-adaption-input{
						                   min-width: 200px;
						               }
						        </style>
						        <!--动态添加数据start-->
						        <div class="scrollTable">
						        	<table id="purchaseOrder" data-toolbar="#toolbar"></table>
						        </div>
						        	
						        <!--动态添加数据end-->
						        <hr/>
						    </form>
						</div>
					</div>
				</div>
			</div>
		</div>
 </body>



<!-- layUI 加载form属性 -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        <!--供应商和供应商合同关联-->
        form.on('select(supplierId)', function (data) {
            var ins = $("#iv").find(".a");
            $("#contractId").empty();
            var html = ""
            for (var i = 0; i < ins.length; i++) {
                if ($(ins[i]).attr("id") == data.value) {
                    var name = $(ins[i]).attr("name");
                    var id = $(ins[i]).attr("value");
                    html += "<option value='" + id + "'>" + name + "</option>";
                }
            }
            $("#contractId").append(html);
            form.render();
        });

    });

</script>
<script type="text/javascript">
	function subForm(){
		var json = new Object();
		json.purchaseDate = $("#createDate").val()==''?null:$("#createDate").val();//采购时间
	    json.contractId=$("#contractId").val()==''?null:$("#contractId").val();//供应商合同
	    json.supplierId=$("#supplierId").val()==''?null:$("#supplierId").val();//供应商id
	  //  json.isTax = $("#isTax").val();//供应商合同 -页面未找到该字段
	    json.remarks = $("#remarks").val();//备注
	    json.invoiceType = $("#invoiceType").val();//付款方式
	  //采购明细单
	    var items = $("#purchaseOrder").find("tbody tr");
	    console.log("items",items);
	    if(null==items || ""==items || items.length==0){
	        layer.alert('请添加sku!', {
	            icon: 2,
	            title: "提示"
	        });
	        return;
	    }
	    var orderItems = new Array();
	    var orderItem;
	    for (var i = 0; i < items.length; i++) {
	        orderItem = new Object();
	        orderItem.skuId = $(items[i]).find("[name='sku']").val();
	        orderItem.price = $(items[i]).find("#price").val();
	        orderItem.num = $(items[i]).find("#num").val();

	        if (orderItem.skuId == "" || orderItem.price == "" || orderItem.num == "") {
	           /*  layer.alert('有空数据请检查!', {
	                icon: 2,
	                title: "提示"
	            }); */
	            jp.error("有空数据！");
	            return;
	        }

	        orderItems.push(orderItem);
	    }
	    json.items = orderItems;
	    var fromData = new FormData();

	    fromData.append("jsons", JSON.stringify(json)); 
	    //提交数据
 	    $.ajax({
	        url: "${ctx}/purchase/purchaseOrder/savePurchaseOrder",
	        type: "post",
	        data: fromData,
	        contentType: false, // 注意这里应设为false
	        processData: false,
	        beforeSend: function () {
	            index = layer.load(1, {
	                shade: [0.5, '#fff'] //0.1透明度的白色背景
	            });
	        },
	        complete: function () {
	            layer.close(index);
	        },
	        success: function (data) {
	            if (data.message == "1") {
	                layer.alert('保存成功!', {
	                    icon: 1,
	                    title: "提示"
	                });
	                layer.close(index);
	                reBack();
	            }
	        },
	        error: function (e) {
	            layer.alert('保存失败!', {
	                icon: 2,
	                title: "提示"
	            });

	        }
	    }); 
	}
</script>
<script>
    <!--返回方法-->
    function reBack() {
        window.location.href = "${ctx}/purchase/purchaseOrder/list";
    }



</script>
<%-- <scrip src="${ctxStatic}/purchase/add_purchase.js"></scrip> --%> 
 <script src="${ctxStatic}/plugin/bootstrapTable/bootstrap-table.js"></script> 
<script src="${ctxStatic}/plugin/bootstrapTable/bootstrap-table-zh-CN.js"></script>  
<script>
var oneKey=false;
function create(){
	oneKey=true;
	$('#purchaseOrder').bootstrapTable('destroy');
	if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端
		 	$('#purchaseOrder').bootstrapTable({
		    	   url: "${ctx}/sc/stockout/findSkuNotStockout",
		    	   contentType : "application/x-www-form-urlencoded",   //必须有
		    	   striped: true,
		    	   onExpandRow: onExpandRow,
		    	 //  responseHandler: responseHandler,//格式化数据      
		    	   detailView: true,//父子表
		    	   //显示切换手机试图按钮
		         //  showToggle: true,
		    	   columns: [
		    		   {
		    			   title:'详情',
		    			   formatter:function(value,row,index){
		    				   return '<span onclick="showSubTab('+row.id+')">点我看详情<span>';
		    			   }
		    		   },
		    		   {
		    	           title: '序号', //标题 可不加
		    	           field:'scount',
		    	           formatter: function (value, row, index) {
		    	               return index + 1;
		    	           }
		    	       },
		    		   {
		    			   title:'SKUID',
		    			   field:'skuId',
			               formatter:function(value,row,index){
			        	     return '<input class="noborder" value='+row.skuId+' name="sku" readOnly>';
			               },
		    	           class:'col-sm-1'
		    		   },
		    		   {
		    		       field:'skuName',
			               title: 'SKU',
		    	           class:'col-sm-3'
			           },
			           {
			               field: 'amount',
			               title: '采购数量',
			               class:'no-padding col-sm-1',
			               formatter:function(value,row,index){
			        	     return '<input class="form-input" value='+row.amount+' onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
			               }
			           }, {
			               title: '采购单价',
			               class:'no-padding col-sm-1',
			               formatter:function(){
			            	  return '<input class="form-input" placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
			               }
			          }, {
			               title: '操作',
			               formatter:function(){
			        	     return "<button class='btn btn-danger table-btn ' onclick='removeItem(this)'>删除</button>"
			               }
			     
			          }
			   ]
		    }); 
		 	$('#purchaseOrder').bootstrapTable("toggleView");
	}else{
	 	$('#purchaseOrder').bootstrapTable({
	    	   url: "${ctx}/sc/stockout/findSkuNotStockout",
	    	   contentType : "application/x-www-form-urlencoded",   //必须有
	    	   striped: true,
	    	   onExpandRow: onExpandRow,
	    	 //  responseHandler: responseHandler,//格式化数据      
	    	   detailView: true,//父子表
	    	   //显示切换手机试图按钮
	         //  showToggle: true,
	    	   columns: [
	    		   {
	    	           title: '序号', //标题 可不加
	    	           field:'scount',
	    	           formatter: function (value, row, index) {
	    	               return index + 1;
	    	           },
	    	           class:'col-sm-1'
	    	          // width:'5%'
	    	       },
	    		   {
	    			   title:'SKUID',
	    			   field:'skuId',
	    	         //  width:'5%',
		               formatter:function(value,row,index){
		        	     return '<input class="noborder" value='+row.skuId+' name="sku" readOnly>';
		               },
	    	           class:'col-sm-1'
	    		   },
	    		   {
	    		       field:'skuName',
		               title: 'SKU',
	    	           class:'col-sm-3'
	    	          // width:'50%'
		           },
		           {
		               field: 'amount',
		               title: '采购数量',
		               class:'no-padding col-sm-1',
	    	          // width:'15%',
		               formatter:function(value,row,index){
		        	     return '<input class="form-input" value='+row.amount+' onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
		               }
		           }, {
		               title: '采购单价',
		               class:'no-padding col-sm-1',
	    	          // width:'15%',
		               formatter:function(){
		            	  return '<input class="form-input" placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
		               }
		          }, {
		               title: '操作',
		               formatter:function(){
		        	     return "<button class='btn btn-danger table-btn ' onclick='removeItem(this)'>删除</button>"
		               }
		     
		          }
		   ]
	    }); 
	}
	

 	
}

    //弹窗选择sku
    function sub() {
        layer.open({
            type: 2,
            title: 'sku选择',
            maxmin: true, //开启最大化最小化按钮*!/
            area: ['96%', '80%'],
            offset: '10px',
            content:ctx+"/sku/sku/pop",
            btn:['确定','取消'],
            yes : function(index,layero) {
                var rows=$(layero).find("iframe")[0].contentWindow.$("#skuTable").bootstrapTable('getSelections');
                if(null!=rows){
                	 var count = $('#purchaseOrder').bootstrapTable('getData').length;
                	 if(count>1){
                         $.each(rows,function(idx,o){
                        	 let skuName=o.productName+"：" + "["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_a'))}, o.categoryA, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_b'))},o.categoryB, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_c'))}, o.categoryC, "-")+"]";
                             let res=checkSkuName(o.id);//校验是否重复
                             if(!res){
                            	 if(oneKey){
                            		 $('#purchaseOrder').bootstrapTable('insertRow',{
                                 		 index:count,
                                 		 row: {
                                 			 scount:count+1,
                                 			 skuId:o.id,
                                 			 amount:'""',
                                 			 skuName:skuName,
                 	                     	}
                                 	 });
                            	 }else{
                            		 $('#purchaseOrder').bootstrapTable('insertRow',{
                                 		 index:count,
                                 		 row: o
                                 	 });
                            	 }
                            	 
                             }
                        });
                	 }else{
                		 oneKey=false;
                		 	$('#purchaseOrder').bootstrapTable({
                		    	   striped: true,
                		    	   data:rows,
                		    	   columns: [
                		    		   {
                		    	           title: '序号', //标题 可不加
                		    	           field:'scount',
                		    	           formatter: function (value, row, index) {
                		    	               return index + 1;
                		    	           },
                		    	           width:'5%'
                		    	       },
                		    		   {
                		    			   title:'SKUID',
                		    	           width:'5%',
                			               formatter:function(value,row,index){
                			            		return '<input class="form-control noborder" value='+row.id+' name="sku" readOnly>';
                			               }
                		    		   },
                		    		   {
                		    		       field:'skuName',
                			               title: 'SKU',
                		    	           width:'50%',
                		    	           formatter:function(value,row,index){
                		    	        	   let skuName=row.productName+"：" + "["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_a'))}, row.categoryA, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_b'))},row.categoryB, "-")+"]" +"—" +"["+jp.getDictLabel(${fns:toJson(fns:getDictList('sc_category_c'))}, row.categoryC, "-")+"]";
                		    	        	   return skuName;
                		    	           }
                			           },
                			           {
                			               field: 'amount',
                			               title: '采购数量',
                		    	           width:'15%',
                			               formatter:function(value,row,index){
                			        	     return '<input class="form-control" value="" onkeyup="checkAmount(this)" name="num" id="num" autocomplete="off" placeholder="请输入采购数量">';
                			               }
                			           }, {
                			               title: '采购单价',
                		    	           width:'15%',
                			               formatter:function(){
                			            	  return '<input class="form-control" placeholder="请输入采购单价" id="price" onkeyup="checkPrice(this)" onblur="checkPrice(this)" name="price" autocomplete="off"/>';
                			               }
                			          }, {
                			               title: '操作',
                			               formatter:function(){
                			        	     return "<button class='btn btn-danger table-btn ' onclick='removeItem(this)'>删除</button>"
                			               }
                			     
                			          }
                			   ]
                		    }); 
                	 }

                }
            }/* ,
            cancel: function(index, layero){ 
              if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                layer.close(index)
              }
              return false; 
            }   */
        });
    }
    //校验sku是否重复
    function checkSkuName(id) {
        var k=0;
        var skus=$("#purchaseOrder").find("input[name='sku']");
        for(var i=0;i<skus.length;i++){
            if(id==$(skus[i]).val()){
                layer.alert('已存在相同的sku!', {
                    icon: 3,
                    title: "提示"
                });
                k=1;
            }
        }
        return k;
    }


    //删除
    function removeItem(obj) {
        $(obj).parents("tr").remove();
    } 
    //采购数量
    function checkAmount(obj){
    	obj.value=obj.value.replace(/\D/g,'');
    }
    function checkPrice(obj){
    	obj.value=obj.value.replace(/[^\d\.]/g,'');
    }
    //查询子表
    function queryParamschild(params){
        return {
            pageSize: params.limit, //页面大小
            pageNo: (params.offset)/10+1 //页码
            
                
        };
    };
  //父子表
    function onExpandRow(index, row, $detail){
        InitSubTable(index, row, $detail);
    }
    InitSubTable = function (index, row, $detail) {
        var cur_table = $detail.html('<table></table>').find('table');
        $(cur_table).bootstrapTable({
            // method: "get", //请求方法
             striped: true, //是否显示行间隔色
             sortable: true, //是否启用排序  
             sortOrder: "asc",  //排序方式 
            // url:ctx+"/finance/generateInvoice"+row.id,
            // dataType: "json",
             pagination: false,    // 显示页码等信息 
             showColumns: false,  // 选择显示的列 
             clickToSelect: false, //在点击行时，自动选择rediobox 和 checkbox
             pageNumber: 1,         //首页页码
             pageSize: 10,           // 当前分页值 
             pageList: [10, 20],  // 分页选页                    
             queryParams: queryParamschild,//传递参数（*）
             sidePagination: 'server',   // //分页方式：client 客户端分页，server 服务端分页
             cache: false, // 不缓存
             striped: true, // 隔行加亮                
            // responseHandler: responseHandler,//格式化数据                 
             columns: [
                 {
                     title: '项目',
                     field: 'projectName',
                     align: 'center',
                     width:'60%'
                 }, 
                 {
                      title: '类型',
                      field: 'type',
                      align: 'center'
                  },
                {
                     title: '数量',
                     field: 'num',
                     align: 'center'
                 }
             ],
             data:[
            	 {
            		 projectName:"华为",
            		 type:"我也不知道",
            		 num:34
            	},
            	{
           			 projectName:"华为2",
           			 type:"我也不知道",
           		 	num:56
	           	},
	           	{
	       		 	projectName:"华为3",
	       		 	type:"我也不知道",
	       		 	num:88
	       	},
             ]
       });
    };
   var showSubTab=function(id){
	   jp.open({
		   type: 1,
		   area: [500, 300],
		   title:"当前sku详情",
		   content:"<div>娃哈哈</div>",
		   btn: ['关闭'],
			  btn1: function(index){
				  jp.close(index);
		       }
	   });
   }
</script>

</html>
